package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Role;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import cn.wolfcode.util.RequirePermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author L5775
 */
@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    // 处理查询请求
    // localhost/role/list.do
    // JSP 查询的数据存到 Model 对象
    @RequestMapping("/list")
    @RequirePermission(name="角色页面",expression = "role:list")
    public String list(Model model, QueryObject qo) {
        PageResult<Role> pageResult = roleService.query(qo);
        model.addAttribute("pageResult", pageResult);
        return "role/list";
    }

    // 处理删除请求
    // http://localhost/role/delete.do?id=1
    // 删除完了还希望浏览器再发送请求访问 localhost/role/list.do
    @RequestMapping("/delete")
    @ResponseBody
    @RequirePermission(name="角色删除",expression = "role:delete")
    public JsonResult delete(Long id) {

            try {
                if (id != null) {
                    roleService.delete(id);
                }
                return new JsonResult();
            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResult(false,"系统异常,请联系管理员");
            }
        }

    // 处理去保存或者去修改请求
    // http://localhost/role/input.do
    @RequestMapping("/input")
    public String input(Long id, Model model) {
        model.addAttribute("permissions",permissionService.listAll());
        if (id != null) {
            model.addAttribute("role",roleService.get(id));
        }
        return "role/input";
    }

    // 处理保存或修改请求
    // http://localhost/role/saveOrUpdate.do 并带了保存员工数据
    // 保存完了还希望浏览器再发送请求访问 localhost/role/list.do
    @RequestMapping("/saveOrUpdate")
    //@ResponseBody
    public String saveOrUpdate(Role role,Long[] ids) {
        if (role.getId() == null) {
            roleService.save(role, ids);
        } else {
            roleService.update(role, ids);
        }
        return "redirect:/role/list.do";
    }
}
